//
//  ShowDetailViewController.m
//  Taste
//
//  Created by 徐昊 on 16/9/13.
//  Copyright © 2016年 徐昊. All rights reserved.
//

#import "ShowDetailViewController.h"
#import "ZWYNetTool.h"
#import "ShowDetailModel.h"
#import "ShowDetailRes.h"
#import "NSString+Vali.h"
#import "UIImageView+WebCache.h"
#import "SelfSizeTool.h"
#import "UIView+Frame.h"
#import "HXMacro.h"
#import "ShowDetailCommentTableViewCell.h"
#import "ShowDetailCommentsModel.h"
#import "ShowDetailCommentsRes.h"
#import "LogInViewController.h"
#import "NSString+HX_TimeInterval.h"

#define kShowDetailCommentsCellName @"ShowDetailCommentsCellNameReuse"
@interface ShowDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *headImg;
@property (weak, nonatomic) IBOutlet UILabel *nickName;
@property (weak, nonatomic) IBOutlet UILabel *content;
@property (weak, nonatomic) IBOutlet UILabel *addtime;
@property (weak, nonatomic) IBOutlet UILabel *praise;
@property (weak, nonatomic) IBOutlet UILabel *commentsCount;
@property (nonatomic, strong) ShowDetailModel *model;
@property (weak, nonatomic) IBOutlet UIImageView *pic;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (nonatomic, strong) ShowDetailCommentsModel *modelOfComments;
@property (weak, nonatomic) IBOutlet UITextField *commentView;
@property (weak, nonatomic) IBOutlet UIImageView *praiseButton;


@end

@implementation ShowDetailViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"秀场详情";
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"LZUniversal_BarButtonItem_Pop"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = back;
    UIBarButtonItem *option = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"LZUniversal_BarButtonItem_More"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(option:)];
    self.navigationItem.rightBarButtonItem = option;
#pragma mark - 点赞图标添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(praise:)];
    _praiseButton.userInteractionEnabled  = YES;
    [_praiseButton addGestureRecognizer:tap];
    
    _headImg.contentMode = UIViewContentModeScaleAspectFill;
    _headImg.clipsToBounds = YES;
    _headImg.layer.masksToBounds = YES;
    [self.view layoutIfNeeded];
    NSLog(@"%f", _headImg.bounds.size.height);
    _headImg.layer.cornerRadius = _headImg.bounds.size.height / 2;
    NSDictionary *dic = @{@"version" : @"2.50",
                          @"Content-Type" : @"application/x-www-form-urlencoded",
                          @"Content-Length" : @"10"};
    [ZWYNetTool POST:@"http://app.legendzest.cn/index3.php?m=api250&c=show&a=getDetail25" andBody:[NSString stringWithFormat:@"sid=%@",_idString] andBodyStyle:ZWYBodyString andHeader:dic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _model = [ShowDetailModel modelWithDic:result];
        [_headImg sd_setImageWithURL:[NSURL URLWithString:[NSString imageWebWithStr:_model.res.headimg]] placeholderImage:[UIImage imageNamed:@"IMG_Universal_Placeholder_Avatar"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        [_pic sd_setImageWithURL:[NSURL URLWithString:[NSString imageWebWithStr:_model.res.pic]] placeholderImage:[UIImage imageNamed:@"IMG_Universal_Placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        _nickName.text = _model.res.nickname;
        _content.text = _model.res.content;
        _addtime.text = [NSString updateTimeForTimeIntervalString:_model.res.addtime];
        _praise.text = [NSString stringWithFormat:@"%@ 人赞过", _model.res.praise];
        _commentsCount.text = [NSString stringWithFormat:@"%@ 条评论", _model.res.commentscount];
        _headerView.h_height = [SelfSizeTool selfSizeHeightWith:_content.text width:self.view.h_width - 63 font:[UIFont systemFontOfSize:17]] + SCREEN_WIDTH + 120;
        _tableView.tableHeaderView = _headerView;
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败");
        
    }];
    NSDictionary *dic1 = @{@"version" : @"2.50",
                          @"Content-Type" : @"application/x-www-form-urlencoded",
                          @"Content-Length" : @"17"};
    NSString *string = [NSString stringWithFormat:@"page=1&sid=%@", _idString];
    [ZWYNetTool POST:@"http://app.legendzest.cn/index3.php?m=api250&c=show&a=getcommentlist25" andBody:string andBodyStyle:ZWYBodyString andHeader:dic1 andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _modelOfComments = [ShowDetailCommentsModel modelWithDic:result];
        [_tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败");
    }];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:@"ShowDetailCommentTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kShowDetailCommentsCellName];
    
}

- (void)back:(UIBarButtonItem *)button {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)option:(UIBarButtonItem *)button {
    
}
#pragma mark - 评论
- (IBAction)comment:(id)sender {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *userUid = [user objectForKey:@"uid"];
    NSString *userUuid = [user objectForKey:@"uuid"];
    if (userUid) {

        NSString *str = [_commentView.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSString *bodyString = [NSString stringWithFormat:@"content=%@&id=%@", str, _model.res.ShowDetail_id];
        NSString *bodyLength = [NSString stringWithFormat:@"%ld", [bodyString length]];
        NSDictionary *dic2 = @{@"uuid" : userUuid,
                               @"version" : @"2.50",
                               @"uid" : userUid,
                               @"Content-Type" : @"application/x-www-form-urlencoded",
                               @"Content-Length" : bodyLength};
        [ZWYNetTool POST:@"http://app.legendzest.cn/index3.php?m=api250&c=user&a=addcomment" andBody:bodyString andBodyStyle:ZWYBodyString andHeader:dic2 andResponse:ZWYJSON andSuccessBlock:^(id result) {
            NSLog(@"请求成功");
            [self reloadPageData];
        } andFailureBlock:^(NSError *error) {
            NSLog(@"请求失败");
        }];
        
    } else {
        LogInViewController *vc = [[LogInViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark - 刷新页面数据
- (void)reloadPageData {
    NSDictionary *dic = @{@"version" : @"2.50",
                          @"Content-Type" : @"application/x-www-form-urlencoded",
                          @"Content-Length" : @"10"};
    [ZWYNetTool POST:@"http://app.legendzest.cn/index3.php?m=api250&c=show&a=getDetail25" andBody:[NSString stringWithFormat:@"sid=%@",_idString] andBodyStyle:ZWYBodyString andHeader:dic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _model = [ShowDetailModel modelWithDic:result];
        [_headImg sd_setImageWithURL:[NSURL URLWithString:[NSString imageWebWithStr:_model.res.headimg]] placeholderImage:[UIImage imageNamed:@"IMG_Universal_Placeholder_Avatar"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        [_pic sd_setImageWithURL:[NSURL URLWithString:[NSString imageWebWithStr:_model.res.pic]] placeholderImage:[UIImage imageNamed:@"IMG_Universal_Placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        _nickName.text = _model.res.nickname;
        _content.text = _model.res.content;
        _addtime.text = _model.res.addtime;
        _praise.text = [NSString stringWithFormat:@"%@ 人赞过", _model.res.praise];
        _commentsCount.text = [NSString stringWithFormat:@"%@ 条评论", _model.res.commentscount];
        _headerView.h_height = [SelfSizeTool selfSizeHeightWith:_content.text width:self.view.h_width - 63 font:[UIFont systemFontOfSize:17]] + SCREEN_WIDTH + 120;
        _tableView.tableHeaderView = _headerView;
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败");
        
    }];
    NSDictionary *dic1 = @{@"version" : @"2.50",
                           @"Content-Type" : @"application/x-www-form-urlencoded",
                           @"Content-Length" : @"17"};
    NSString *string = [NSString stringWithFormat:@"page=1&sid=%@", _idString];
    [ZWYNetTool POST:@"http://app.legendzest.cn/index3.php?m=api250&c=show&a=getcommentlist25" andBody:string andBodyStyle:ZWYBodyString andHeader:dic1 andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _modelOfComments = [ShowDetailCommentsModel modelWithDic:result];
        [_tableView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"请求失败");
    }];
}
#pragma mark - 点赞
- (void)praise:(UITapGestureRecognizer *)button {
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *userUid = [user objectForKey:@"uid"];
    NSString *userUuid = [user objectForKey:@"uuid"];
    if (userUid) {
        NSString *bodyString = [NSString stringWithFormat:@"id=%@", _model.res.ShowDetail_id];
        NSString *bodyLength = [NSString stringWithFormat:@"%ld", [bodyString length]];
        NSDictionary *dic2 = @{@"uuid" : userUuid,
                               @"version" : @"2.50",
                               @"uid" : userUid,
                               @"Content-Type" : @"application/x-www-form-urlencoded",
                               @"Content-Length" : bodyLength};
        [ZWYNetTool POST:@"http://app.legendzest.cn/index3.php?m=api250&c=user&a=praiseShow" andBody:bodyString andBodyStyle:ZWYBodyString andHeader:dic2 andResponse:ZWYJSON andSuccessBlock:^(id result) {
            NSLog(@"%@", result);
            [self reloadPageData];
            NSLog(@"请求成功");
        } andFailureBlock:^(NSError *error) {
            NSLog(@"请求失败");
        }];
    } else {
        LogInViewController *vc = [[LogInViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_modelOfComments.res[indexPath.row].replayname) {
        return [SelfSizeTool selfSizeHeightWith:[NSString stringWithFormat:@"回复 %@: %@", _modelOfComments.res[indexPath.row].replayname, _modelOfComments.res[indexPath.row].content] width:self.view.h_width - 60 font:[UIFont systemFontOfSize:17]] + 50;
    } else {
        return [SelfSizeTool selfSizeHeightWith:_modelOfComments.res[indexPath.row].content width:self.view.h_width - 60 font:[UIFont systemFontOfSize:17]] + 50;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _modelOfComments.res.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ShowDetailCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kShowDetailCommentsCellName];
    cell.res = _modelOfComments.res[indexPath.row];
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
